import {
  recordClient,
  getClientFromRequest,
  getRecordClient,
  LINK_MODE
} from '../service'

import {
  colorconsole
} from '../lib/utils'

const CLIENT_PORT = 39517
/**
 * 记录最新的用户进入的请求
 */
export async function logger (context, next) {
  try {
    const { pathClientLog } = context.conf.defaults
    const { sn, clientIp, linkMode } = getClientFromRequest(context.request)
    let client = {
      sn: sn,
      ip: clientIp,
      port: CLIENT_PORT
    }
    switch (linkMode) {
      case LINK_MODE.WIFI:
        colorconsole.info(`### App Server ### 记录从${clientIp}进入的HTTP请求`)
        recordClient(pathClientLog, client)
        break
      case LINK_MODE.ADB:
        // ADB模式下需要先读取连接时记录的信息
        client = getRecordClient(pathClientLog, sn, clientIp)
        if (client) {
          colorconsole.info(`### App Server ### 记录从设备(${sn})进入的HTTP请求`)
          recordClient(pathClientLog, client)
        }
        else {
          colorconsole.warn(`### App Server ### ：记录设备(${sn})失败`)
        }
        break
    }
    await next()
  }
  catch (err) {
    colorconsole.error(`### App Server ### 记录log出错: ${err.message}`)
  }
}

export async function errorHandler (context, next) {
  try {
    await next() 
  } catch (e) {
    context.body = {
      message: e.message,
      code: e.status || 500
    }
    // 传递给上层logger中间件
    throw new Error(`${e.status || 500}, ${e.message}`)
  }
}

export default {
  logger,
  errorHandler
}
